import styles from './index.module.less'
import Copy from 'clipboard'
import cm from 'classnames'
import Toast from '@/components/toast'
import { shareLink } from '@/store'
import { useEffect } from 'react'
import { useRecoilState } from 'recoil'
import { getLink } from '@/api'

const Index = () => {
  const [link, setLink] = useRecoilState(shareLink)
  const fetchShareLink = async () => {
    const res = await getLink()
    if (!res.code) {
      setLink(res.data?.link)
    }
  }
  useEffect(() => {
    if (!link) {
      fetchShareLink()
    }
    const copyUrl = new Copy('.line-btn')
    copyUrl.on('success', () => {
      Toast.normal('已成功复制到剪切板')
    })
    return () => {
      copyUrl.destroy()
    }
  }, [])
  return (
    <div className={styles.linkContainer}>
      <img src="/images/link-bg.webp" className={styles.linkBg} />
      <div className={styles.content}>
        <p className={styles.slogan}>邀请用户开始赚钱</p>
        <div className={styles.copy}>
          <p className={styles.copyText}>{link}</p>
          {link && (
            <div className={cm(styles.copyBtn, 'line-btn')} data-clipboard-text={link}>
              复制推广链接
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default Index
